package com.qzw.study.xml;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @author 屈子威
 * @date 2020/9/16 4:39
 * @description
 */
@Configuration
public class SelfBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean.getClass().getAnnotation(Component.class) != null) {
			Field[] fields = bean.getClass().getDeclaredFields();
			for (Field field : fields) {
				if (field.getAnnotation(Autowired.class) != null || field.getAnnotation(Resource.class) != null) {
					field.setAccessible(true);
					if (field.getType().getAnnotation(Repository.class) != null) {
						//发现如果注入的是DAO就设置为null
						//当然为了不让Controller注入DAO 也可以直接抛出异常
						throw new RuntimeException("Controller Not Allowed Autowired Dao");
					}
				}
			}
		}
		return bean;
	}
}
